import {
  ProCard,
  ProForm,
  ProFormCheckbox,
  ProFormDatePicker,
  ProFormDateRangePicker,
  ProFormSelect,
  ProFormText,
  ProFormTextArea,
  StepsForm,
  ProFormDependency,
} from '@ant-design/pro-components';
import { UploadOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import type { UploadProps } from 'antd';
import { Button, message, Upload, Form, Input, Card } from 'antd';
import React from 'react';

const formItemLayout = {
  labelCol: {
    xs: { span: 24 },
    sm: { span: 4 },
  },
  wrapperCol: {
    xs: { span: 24 },
    sm: { span: 20 },
  },
};

const formItemLayoutWithOutLabel = {
  wrapperCol: {
    xs: { span: 24, offset: 0 },
    sm: { span: 20, offset: 4 },
  },
};
const waitTime = (time: number = 100) => {
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(true);
    }, time);
  });
};

const props: UploadProps = {
  name: 'file',
  action: 'https://www.mocky.io/v2/5cc8019d300000980a055e76',
  headers: {
    authorization: 'authorization-text',
  },
  onChange(info) {
    if (info.file.status !== 'uploading') {
      console.log(info.file, info.fileList);
    }
    if (info.file.status === 'done') {
      message.success(`${info.file.name} file uploaded successfully`);
    } else if (info.file.status === 'error') {
      message.error(`${info.file.name} file upload failed.`);
    }
  },
};
export default () => {
  const onFinish = (values: any) => {
    console.log('Received values of form:', values);
  };
  return (
    <ProCard>
      <StepsForm<{
        name: string;
      }>
        onFinish={async (values) => {
          console.log(values);
          await waitTime(1000);
          message.success('提交成功');
        }}
        formProps={{
          validateMessages: {
            required: '此项为必填项',
          },
        }}
        submitter={{
          render: (props) => {
            if (props.step === 0) {
              return (
                <Button type="primary" onClick={() => props.onSubmit?.()}>
                  去第二步 {'>'}
                </Button>
              );
            }

            if (props.step === 1) {
              return [
                <Button key="pre" onClick={() => props.onPre?.()}>
                  返回第一步
                </Button>,
                <Button type="primary" key="goToTree" onClick={() => props.onSubmit?.()}>
                  去第三步 {'>'}
                </Button>,
              ];
            }

            return [
              <Button key="gotoTwo" onClick={() => props.onPre?.()}>
                {'<'} 返回第二步
              </Button>,
              <Button type="primary" key="goToTree" onClick={() => props.onSubmit?.()}>
                提交 √
              </Button>,
            ];
          },
        }}
      >
        <StepsForm.StepForm<{
          name: string;
        }>
          name="base"
          title="新建通知"
          onFinish={async ({ name }) => {
            console.log(name);
            await waitTime(2000);
            return true;
          }}
        >
          <ProFormText
            name="name"
            label="通知名称"
            width="md"
            tooltip="最长为 24 位，用于标定的唯一 id"
            placeholder="请输入名称"
            rules={[{ required: true }]}
          />
          <ProFormDatePicker name="date" label="创建日期" />
          <ProFormTextArea name="remark" label="通知内容" width="lg" placeholder="请输入通知内容" />
        </StepsForm.StepForm>
        <StepsForm.StepForm<{
          checkbox: string;
        }>
          name="checkbox"
          title="选择通知对象"
        >
          <ProFormSelect
            name={['number']}
            label="对象范围"
            width="lg"
            rules={[
              {
                required: true,
              },
            ]}
            options={[
              { value: '0', label: '专业' },
              { value: '1', label: '年级' },
              { value: '2', label: '班级' },
              { value: '3', label: '自定义分群' },
            ]}
          />
          <ProFormDependency name={[['number']]}>
            {({ number }) => {
              if (number == '0') {
                return (
                  <ProFormSelect
                    mode="multiple"
                    width="lg"
                    name="major"
                    rules={[{ required: true, message: '请选择专业' }]}
                    label="专业"
                    options={[
                      { value: '1', label: '电气' },
                      { value: '2', label: '新能' },
                    ]}
                    placeholder="请选择专业"
                  />
                );
              } else if (number == '1') {
                return (
                  <ProFormSelect
                    mode="multiple"
                    width="lg"
                    name="grade"
                    rules={[{ required: true, message: '请选择年级' }]}
                    label="年级"
                    options={[{ value: '1', label: '2023' }]}
                    placeholder="请选择年级"
                  />
                );
              } else if (number == '2') {
                return (
                  <ProFormSelect
                    mode="multiple"
                    width="lg"
                    name="class"
                    rules={[{ required: true, message: '请选择班级' }]}
                    label="班级"
                    options={[
                      { value: '1', label: '电气2301班' },
                      { value: '2', label: '电气2302班' },
                      { value: '3', label: '电气2303班' },
                      { value: '4', label: '电气2304班' },
                      { value: '5', label: '电气2305班' },
                      { value: '6', label: '电气2306班' },
                      { value: '7', label: '电气2307班' },
                      { value: '8', label: '电气2308班' },
                    ]}
                    placeholder="请选择班级"
                  />
                );
              } else if (number == '3') {
                return (
                  <ProFormSelect
                    mode="multiple"
                    width="lg"
                    name="group"
                    rules={[{ required: true, message: '请选择自定义分群' }]}
                    label="自定义分群"
                    options={[
                      { value: '1', label: '团员' },
                      { value: '2', label: '党员' },
                      { value: '3', label: '夏令营参与人员' },
                    ]}
                    placeholder="请选择自定义分群"
                  />
                );
              }
            }}
          </ProFormDependency>
        </StepsForm.StepForm>
        <StepsForm.StepForm name="time" title="附件/自定义表单设置">
          <ProFormSelect
            name={['number']}
            label="自定义模式选择（仅支持选择一种）"
            width="lg"
            rules={[
              {
                required: true,
              },
            ]}
            options={[
              { value: '0', label: '输入框' },
              { value: '1', label: '单选框' },
            ]}
          />
          <ProFormDependency name={[['number']]}>
            {({ number }) => {
              if (number == '0') {
                return (
                  <Card title="输入框" bordered={false} style={{ width: 600 }}>
                    <ProFormText
                      name="name"
                      label="输入框名称"
                      width="md"
                      placeholder="请输入名称"
                      rules={[{ required: true }]}
                    />
                  </Card>
                );
              } else if (number == '1') {
                return (
                  <Card title="选项（请勿保留空选项）" bordered={false} style={{ width: 600 }}>
                    <Form
                      name="dynamic_form_item"
                      {...formItemLayoutWithOutLabel}
                      onFinish={onFinish}
                      style={{ maxWidth: 600 }}
                    >
                      <Form.List
                        name="names"
                        rules={[
                          {
                            validator: async (_, names) => {
                              if (!names || names.length < 2) {
                                return Promise.reject(new Error('请至少输入两个选项'));
                              }
                            },
                          },
                        ]}
                      >
                        {(fields, { add, remove }, { errors }) => (
                          <>
                            {fields.map((field, index) => (
                              <Form.Item {...field} required={false} key={field.key}>
                                <Form.Item
                                  {...field}
                                  validateTrigger={['onChange', 'onBlur']}
                                  rules={[
                                    {
                                      required: true,
                                      whitespace: true,
                                      message: '请输入选项内容或删除该空选项',
                                    },
                                  ]}
                                  noStyle
                                >
                                  <Input placeholder="选项名称" style={{ width: '60%' }} />
                                </Form.Item>
                                {fields.length > 1 ? (
                                  <MinusCircleOutlined
                                    className="dynamic-delete-button"
                                    onClick={() => remove(field.name)}
                                  />
                                ) : null}
                              </Form.Item>
                            ))}
                            <Form.Item>
                              <Button
                                type="dashed"
                                onClick={() => add()}
                                style={{ width: '60%' }}
                                icon={<PlusOutlined />}
                              >
                                添加选项
                              </Button>
                              <Form.ErrorList errors={errors} />
                            </Form.Item>
                          </>
                        )}
                      </Form.List>
                    </Form>
                  </Card>
                );
              }
            }}
          </ProFormDependency>

          <Card title="附件（如不需要，可不上传附件）" bordered={false} style={{ width: 600 }}>
            <Upload {...props}>
              <Button icon={<UploadOutlined />}>上传附件</Button>
            </Upload>
          </Card>
        </StepsForm.StepForm>
      </StepsForm>
    </ProCard>
  );
};
